package com.freedom.monitor.myeye.metrics.server.utils;

import com.alibaba.fastjson.JSONObject;
import com.freedom.rpc.thrift.common.utils.Logger;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaders.Names.SERVER;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class NettyUtils {
	private static final Logger logger = Logger.getLogger(NettyUtils.class);

	public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
		// 构造响应体
		JSONObject object = new JSONObject();
		object.put("error", 1);
		object.put("status", status.toString());
		// 设置到response对象
		final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
				Unpooled.copiedBuffer(object.toJSONString(), CharsetUtil.UTF_8));
		response.headers().set(CONTENT_TYPE, ConstantsUtils.JSON);
		response.headers().set(Names.CONNECTION, "close");
		response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
		response.headers().set(SERVER, ConstantsUtils.SERVER);

		// 发送
		// Close the connection as soon as the error message is sent.
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}

	// public static void sendSuccesstTest(ChannelHandlerContext ctx,
	// HttpResponseStatus status, FullHttpRequest request) {
	// FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
	// status);
	// // boolean keepAlive = HttpHeaders.isKeepAlive(request);
	// // response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
	// // 设置header
	// response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
	// response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE);
	// // 设置body
	// ByteBuf buffer = Unpooled.copiedBuffer("Success: " + status + "-" +
	// System.currentTimeMillis() + "\r\n",
	// CharsetUtil.UTF_8);
	// response.content().writeBytes(buffer);
	// buffer.release();
	// // 发射&强制关闭连接
	// ChannelFuture future = ctx.writeAndFlush(response);
	// future.addListener(ChannelFutureListener.CLOSE);
	// logger.debug("handle http request end");
	// }
}
